package com.project8.main;


import java.io.EOFException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
import com.project8.book.Book;
import com.project8.book.Chapter;
import com.project8.book.Page;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.*;
import android.graphics.drawable.BitmapDrawable;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.TypedValue;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;


public class Bookshelf extends Activity{
	
	
	private int numBooks = 0;
	private ImageView add;
	private LinearLayout addContainer; 
	private TextView cantAdd;
	
	//Array of File Names
	private String[] fileNames = null;

	
	ArrayList<TableRow> tr;
	ArrayList<ImageView> thumbnail;
	ArrayList<TextView> title;
	ArrayList<LinearLayout> ll;
	
	//Internal Storage
	private static final String internalStorage= Environment.getExternalStorageDirectory() + "/Textbooks/";
	
	Context appContext;
	private int bookToDelete;
	boolean finished;

	@SuppressWarnings("unchecked")
	@Override  
	public void onCreate(Bundle savedInstanceState) {
		 	
		super.onCreate(savedInstanceState);  
		
		appContext = this;
		
		SeekBar brightnessBar = brightnessBar = (SeekBar)findViewById(R.id.brightnessBar);
		BrightnessSettings bright = new BrightnessSettings(this, brightnessBar, getWindow(), getContentResolver());
			
		ObjectInputStream inputStream = null;
        
        try {
            
            //Construct the ObjectInputStream object
            inputStream = new ObjectInputStream(new FileInputStream("mnt/sdcard/Books"));
            
            Global.books = (ArrayList<Book>) inputStream.readObject();
            
            System.out.println("Book Size: " + Global.books.size());
            
         
        } catch (EOFException ex) { //This exception will be caught when EOF is reached
            System.out.println("End of file reached.");
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            //Close the ObjectInputStream
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
		
		
		
		
		if(Global.books.size() == 0)
		{
			File booksInDirectory = new File(internalStorage);
			
			booksInDirectory.mkdir();
			
			//Create List of Books in the Books Directory			
			fileNames = booksInDirectory.list();
			
			numBooks = fileNames.length;
			
			if(numBooks > 0)
			{
				for(int b = 0; b < fileNames.length; b++)
				{
					Global.books.add(new Book(fileNames[b]));
				}
			}
		}
	}//End OnCreate
	
	@Override
	public void onResume()
	{
	    super.onResume();
	    refreshBookshelf();
	}
	
	public void refreshBookshelf()
	{		
		int row = 0;
		int column = 0;
				
		numBooks = Global.books.size();
		
		tr = new ArrayList<TableRow>();
		thumbnail = new ArrayList<ImageView>();
		title = new ArrayList<TextView>();
		ll = new ArrayList<LinearLayout>();
		
		
		
		//Create a scrollable container that is the size of the screen
		ScrollView Scroll = new ScrollView(this);
	    Scroll.setFillViewport(true);
		
		//Bookshelf uses a 2 column width table layout
	    TableLayout table = new TableLayout(this);
	    table.setScrollContainer(true);
	    table.setStretchAllColumns(true);  
	    table.setShrinkAllColumns(true);
	    table.setBackgroundColor(Color.WHITE);
	    
	    
	    //Title Row with a text view
	    TableRow rowTitle = new TableRow(this);
	    //rowTitle.setGravity(Gravity.LEFT);
	    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.titlebg);
	    BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
	    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT, Shader.TileMode.REPEAT);
	    rowTitle.setBackgroundDrawable(bitmapDrawable);
	    
	    TextView header = new TextView(this);  
	    header.setText("Bookshelf");  
	    header.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 22); 
	    header.setGravity(Gravity.LEFT);
	    header.setTextColor(Color.parseColor("White"));
	    header.setPadding(20, 0, 0, 0);
	    header.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
	    addContainer = new LinearLayout(this);
	    
	    
	    if(isOnline())
	    {
	   	    add = new ImageView(this);
		    add.setImageResource(R.drawable.icon_add);
		    add.setOnClickListener(new View.OnClickListener() {  			 	
			 	public void onClick(View v) {					
			 		ProgressDialog P = new ProgressDialog(appContext);
			 		P.setMessage("Updating Book List");
			 		
			 		new BookListUpdater(P, appContext).execute();

	            }
	        });
		    
		 	
		    /* Just makes it more obvious to the user that they have touched the Add button */
		    add.setOnTouchListener(new View.OnTouchListener() {
				public boolean onTouch(View v, MotionEvent event) 
				{
					if(event.getAction() == MotionEvent.ACTION_DOWN)
					{
						add.setImageResource(R.drawable.icon_add_touched);
					}
					else if(event.getAction() == MotionEvent.ACTION_UP)
					{
						add.setImageResource(R.drawable.icon_add);
						add.performClick();
					}
					
					return true;
				}
        	});
	    }
	    else
	    {
		    cantAdd = new TextView(this);
		    cantAdd.setText("No Internet Connection");
		    cantAdd.setTextColor(Color.parseColor("White"));
		    cantAdd.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
		    cantAdd.setPadding(0, 8, 0, 0);
		}
	   
	    
	    //Title Row will span two columns
	   
	    rowTitle.addView(header);
	    
	    if(isOnline())
	    {
	    	addContainer.addView(add);
	    	addContainer.setGravity(Gravity.RIGHT);
	    	addContainer.setPadding(0, 0, 20, 0);
	    	rowTitle.addView(addContainer);
	    	
	    }
	    else
	    {
	    	addContainer.addView(cantAdd);
	    	addContainer.setGravity(Gravity.RIGHT);
	    	addContainer.setPadding(0, 0, 10, 0);
	    	rowTitle.addView(addContainer);
	    }
	    
	    table.addView(rowTitle);
		
		//Create the first Table Row for Layout and add to Table
	    tr.add(new TableRow(getApplicationContext()));
	    tr.get(0).setPadding(0, 25, 0, 25);
		table.addView(tr.get(0));

	    if(numBooks > 0)
	    {	
	    	
    		//Main Looping Through all books
	    	for(int i = 0; i < numBooks; i++){
	    		 	    	 
	    		 //Every 2 Books make new Row
	    		//if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
	    			column = (i + 1) % 2;
	    		//else
	    		//	column = (i + 1) % 3;
	    		 
	    		 //If it is the First Column Dynamically Create a new TableRow
	    		 if(i > 1 && column >0)
	    		 {
	    			 //Create a New Row and increment number of rows counter
	    			 row++;
	    			 tr.add(new TableRow(getApplicationContext()));
	    			 tr.get(row).setPadding(0, 25, 0, 25);
	    			 table.addView(tr.get(row));
	    		 }
	    		 
	    		 	    		 
			 	 //Create an ImageView of Book Thumbnail
			 	 thumbnail.add(new ImageView(getApplicationContext()));
			 	 
			 	 //Set Id for OnClick Event
			     thumbnail.get(i).setId(i);
	    		 
			     /*
	    	     * Read Each Thumbnail Image from Directory <BookName>/thumbnail.png
	    	     */  				     
	    	     Bitmap bm = BitmapFactory.decodeFile(internalStorage + Global.books.get(i).getBookTitle() + "/thumbnail.png");
				 thumbnail.get(i).setImageBitmap(bm);
	    		
				 
			    
				
	    		 //Create OnClick Event for each Thumbnail
	    		 thumbnail.get(i).setOnClickListener(new View.OnClickListener() 
	    		 {  			 	
	    			 	public void onClick(View v) 
	    			 	{
	    			 		if(!Global.books.get(v.getId()).isGenerated())
	    			 		{
	    			 			ProgressDialog P = new ProgressDialog(appContext);
	    				 		P.setMessage("Updating Book List");
	    			 			new BookGenerator(P, appContext, Global.books.get(v.getId()).getBookTitle(), v.getId()).execute();
	    			 		}
	    			 		else
	    			 		{
	    			 			//Bundle Up Book
								Bundle bun = new Bundle();
								//bun.putSerializable("Book", books.get(v.getId()));
								bun.putInt("bookIndex", v.getId());
								//Start Main App
								Intent myIntent = new Intent(v.getContext(), Main.class);
		    	            	myIntent.putExtras(bun);  	            	
		    	                startActivity(myIntent);
	    			 		}   			 		
	    			 			    					
	    	            }
	    	     });
	    		 
    		 	    	    
				 //Create Text View to Show Book Title underneath Thumbnail
				 title.add(new TextView(getApplicationContext()));
				 title.get(i).setText(Global.books.get(i).getBookTitle());
    			 title.get(i).setGravity(Gravity.CENTER);
    			 title.get(i).setPadding(10, 10, 10, 10);
    			 title.get(i).setTextColor(Color.parseColor("Black"));
    			 
    			 //Create Linear Layout to Display Book Cover and Book Title Vertically
    			 ll.add(new LinearLayout(getApplicationContext()));
    			 ll.get(i).setOrientation(LinearLayout.VERTICAL);  
    			 ll.get(i).setGravity(Gravity.CENTER); 
    			 
    			 //Add Thumbnail and Book Title to Linear Layout
    			 ll.get(i).addView(thumbnail.get(i));
    			 ll.get(i).addView(title.get(i));
    			 
    			 
    			 
    			 registerForContextMenu(thumbnail.get(i));
    			 registerForContextMenu(title.get(i));
    			     			 
	    		 //Add thumbnail to Row
	    		 tr.get(row).addView(ll.get(i));
	    		 
	    	}//End Book Loop
	   	
	    }//End If
	    else
	    {
	    	System.out.println("No Books");
	    }
	    
	    
	    //Add Table to Scroll Container
	    Scroll.addView(table);
	    
	    //Set the content View to be the Scrolling Bookshelf
	    setContentView(Scroll);	
	    
	}
	
	  @Override  
	public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
	    super.onCreateContextMenu(menu, v, menuInfo);  
	   
	    menu.setHeaderTitle("Delete Book");  
	    menu.add(0, v.getId(), 0, "Delete Book");
	    
	    bookToDelete = v.getId();
	}
	  
    @Override  
	public boolean onContextItemSelected(MenuItem item) {  
	  
	  File deleteDirectory = new File(internalStorage + Global.books.get(bookToDelete).getBookTitle());
	  
	  this.deleteDir(deleteDirectory);
	  
	  if(Global.books.size() > 0 && bookToDelete < Global.books.size())
	  {
		 Global.books.remove(bookToDelete);
	  }
	  
	  refreshBookshelf();
	  
	  return true ;
	} 
    
	// Deletes all files and subdirectories under dir.
	// Returns true if all deletions were successful.
	// If a deletion fails, the method stops attempting to delete and returns false.
	public boolean deleteDir(File dir) {
	    if (dir.isDirectory()) {
	        String[] children = dir.list();
	        for (int i=0; i<children.length; i++) {
	            boolean success = deleteDir(new File(dir, children[i]));
	            if (!success) {
	                return false;
	            }
	        }
	    }
	
	    // The directory is now empty so delete it
	    return dir.delete();
	}
	
	
	
	public boolean isOnline() {
			 
		 ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		 
		 if(cm.getActiveNetworkInfo() == null)
		 {
			 return false;
		 }
		 else
		 {
			 return cm.getActiveNetworkInfo().isConnected();
		 }
		 

	}
	
	
	
	
	@Override
	public void onConfigurationChanged(Configuration newConfig) 
	{		
		super.onConfigurationChanged(newConfig);
		
		refreshBookshelf();
	}
	
	
}//End Class


